<template>
  <div class="app-container aliy">
    <el-form
      v-show="showSearch"
      ref="queryForm"
      :inline="true"
      :model="queryParams"
      label-width="68px"
      size="small"
    >
      <el-form-item label="" prop="machineType" label-width="100px">
        <el-input
          v-model="queryParams.machineType"
          clearable
          placeholder="请输入机台类型名称"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <!-- <el-form-item
        label="所属门店"
        prop="type"
        v-hasPermi="['machine:machineType:store']"
      >
        <el-select
          v-model="queryParams.storeName"
          placeholder="请选择门店"
          style="width: 100%"
        >
          <el-option
            v-for="item in storeOptions"
            :key="item.storeId"
            :label="item.storeName"
            :value="item.storeName"
          >
          </el-option>
        </el-select>
      </el-form-item> -->

      <el-form-item>
        <el-button
          icon="el-icon-search"
          size="mini"
          type="primary"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['machine:machineType:add']"
          >新增</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>
    <el-table
      :header-cell-style="{ background: '#f4f3f9', color: '#606266' }"
      border
      v-loading="loading"
      :data="machineTypeList"
      @selection-change="handleSelectionChange"
      @row-click="handleRowClick"
    >
      <el-table-column align="center" label="ID" width="80" prop="id">
      </el-table-column>
      <el-table-column align="center" label="图片" prop="imgURL">
        <template #default="{ row }">
          <el-avatar
            class="img"
            shape="square"
            :size="110"
            :src="img_url + row.imgURL"
          ></el-avatar>
        </template>
      </el-table-column>
      <el-table-column align="center" label="名称" prop="machineType" />
      <el-table-column align="center" label="创建人" prop="createdBy" />
      <el-table-column
        align="center"
        label="创建时间"
        prop="createdTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{
            parseTime(scope.row.createdTime, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="更新人" prop="updatedBy">
        <template slot-scope="scope">
          {{ scope.row.updatedBy === null ? "暂无" : scope.row.updatedBy }}
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        label="更新时间"
        prop="updatedTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{
            scope.row.updatedTime === null
              ? "暂无"
              : parseTime(scope.row.updatedTime, "{y}-{m}-{d} {h}:{i}:{s}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        class-name="small-padding fixed-width"
        label="操作"
      >
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['machine:machineType:edit']"
            icon="el-icon-edit"
            size="mini"
            type="text"
            @click="handleUpdate(scope.row)"
            >修改
          </el-button>
          <el-button
            v-if="![1,2,3,4].includes(scope.row.id)"
            v-hasPermi="['machine:machineType:remove']"
            icon="el-icon-delete"
            size="mini"
            type="text"
            @click="handleDelete(scope.row)"
            >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 下一页 -->
    <pagination
      v-show="total > 0"
      :limit.sync="queryParams.pageSize"
      :page.sync="queryParams.pageNum"
      :total="total"
      @pagination="getList"
    />

    <!-- 添加或修改机台类型对话框 -->
    <el-dialog :title="title" :visible.sync="open" append-to-body width="600px">
      <el-form ref="form" :model="form" :rules="rules" label-width="150px" label-position="left">
        <el-form-item
          label="机台类型名称"
          prop="machineType"
        >
          <el-col :span="16">
            <el-input 
              v-model="form.machineType" 
              placeholder="请输入机台类型名称" 
              style="margin-left: 6px;"
              size="medium"
            />
          </el-col>
        </el-form-item>
        <el-form-item label="是否占位" prop="isReserveASeat" label-width="150px">
          <el-col :span="16">
            <el-radio-group v-model="form.isReserveASeat" style="margin-left: 6px;">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-col>
        </el-form-item>
        <el-form-item label="是否扣币" prop="isDeductCoin" label-width="150px">
          <el-col :span="16">
            <el-radio-group v-model="form.isDeductCoin" style="margin-left: 6px;">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-col>
        </el-form-item>
        <el-form-item label="当前局游戏中是否支持再次投币" prop="isReCoin" label-width="150px">
          <el-col :span="16">
            <div style="margin-left: 6px;">
              <div style="margin-top: 8px;">
                <el-radio-group v-model="form.isReCoin">
                  <el-radio :label="1">是</el-radio>
                  <el-radio :label="0">否</el-radio>
                </el-radio-group>
              </div>
            </div>
          </el-col>
        </el-form-item>
        <el-form-item label="游戏中投币量选项" prop="coinQuantity" label-width="150px">
          <el-col :span="16">
            <el-checkbox-group v-model="form.coinQuantity" style="margin-left: 6px;">
              <el-checkbox 
                v-for="option in coinQuantityAll" 
                :key="option.value" 
                :label="typeof option.value === 'string' ? Number(option.value) : option.value"
              >
                {{ option.label }}
              </el-checkbox>
            </el-checkbox-group>
          </el-col>
        </el-form-item>
        <el-form-item label="游戏功能按钮" prop="gameFunctions" label-width="150px">
          <el-col :span="16">
            <el-checkbox-group v-model="form.gameFunctions" style="margin-left: 6px;">
              <el-checkbox 
                v-for="option in gameFunctionsAll" 
                :key="option.value" 
                :label="typeof option.value === 'string' ? Number(option.value) : option.value"
              >
                {{ option.label }}
              </el-checkbox>
            </el-checkbox-group>
          </el-col>
        </el-form-item>
        <el-form-item label="是否有结算" prop="isSettle" label-width="150px">
          <el-col :span="16">
            <el-radio-group v-model="form.isSettle" style="margin-left: 6px;">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
              <el-radio :label="2">无</el-radio>
            </el-radio-group>
          </el-col>
        </el-form-item>
        <el-form-item label="结算方式" prop="settleType" label-width="150px">
          <el-col :span="16">
            <el-radio-group v-model="form.settleType" style="margin-left: 6px;">
              <el-radio :label="1">分数转换成5G彩票</el-radio>
              <el-radio :label="2">无</el-radio>
            </el-radio-group>
          </el-col>
        </el-form-item>
        <el-form-item label="是否转换成分数" prop="isScore" label-width="150px">
          <el-col :span="16">
            <el-radio-group v-model="form.isScore" style="margin-left: 6px;">
              <el-radio :label="1">是</el-radio>
              <el-radio :label="0">否</el-radio>
            </el-radio-group>
          </el-col>
        </el-form-item>
        <el-form-item label="玩家获得" prop="playerGetType" label-width="150px">
          <el-col :span="16">
            <el-select
              v-model="form.playerGetType"
              placeholder="请选择玩家获得"
              style="margin-left: 6px; width: calc(100% - 1px);"
            >
              <el-option
                v-for="item in playerGetTypeAll"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-col>
        </el-form-item>

        <el-form-item label="图片" prop="imgURL" style="margin-bottom: 2">
          <el-col :span="16">
            <el-upload
              :auto-upload="false"
              :before-upload="beforeUpload"
              :on-change="handleAvatarChangeIcon"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
              :show-file-list="false"
              accept="image/jpeg,image/png"
              action="#"
              style="margin-left: 6px;"
            >
              <i
                v-if="form.imgURL === '' || form.imgURL === null"
                class="el-icon-plus upload"
              ></i>
              <img v-else :src="img_url + form.imgURL" style="width: 100%; height: 150px" />
            </el-upload>
          </el-col>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addMachineType,
  delMachineType,
  getMachineType,
  listMachineType,
  updateMachineType,
  getMachineTypeDict,
} from "@/api/machine/machineType";

import { uploadImg } from "@/api/machine/manage";
import myQuillEditor from "@/components/Editor";

export default {
  name: "MachineType",
  components: {
    myQuillEditor,
  },
  data() {
    return {
      // 图片 前缀url
      img_url: this.imgUrl,
      // 用户信息
      userId: sessionStorage.getItem("userId"),
      deptId: sessionStorage.getItem("deptId"),
      // 所有门店信息
      storeOptions: null,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 机台类型表格数据
      machineTypeList: [],
      // 游戏设置-------------------------------------------------------------
      // 兑率
      exchangeRate: [],
      // 兑出率
      
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        machineType: null,
        createdTime: null,
      },
      // 表单参数
      form: {
        projectDetail: "",
        machineType:"",
        isReserveASeat: null,
        isDeductCoin: null,
        isReCoin: null,
        isSettle: null,
        settleType: null,
        isScore: null,
        coinQuantity: [],
        gameFunctions: [],
        playerGetType: null,
      },
      coinQuantityAll: [],
      gameFunctionsAll: [],
      playerGetTypeAll: [],
      // 表单校验
      rules: {
        ParentId: [
          { required: true, message: "机台名称不能为空", trigger: "blur" },
        ],
        machineType: [
          { required: true, message: "上级机台类型不能为空", trigger: "blur" },
        ],
        imgURL: [
          { required: true, message: "图片不能为空", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getList();
    this.getMachineTypeDict();
  },
  methods: {    
    /** 查询机台类型列表 */
    getList() {
      this.loading = true;
      listMachineType(this.queryParams).then((response) => {
        this.machineTypeList = response.rows;
        this.nameTypeID = null;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 获取机台类型字典
    getMachineTypeDict() {
      getMachineTypeDict().then((response) => {
        this.coinQuantityAll = response.data.coinQuantityAll;
        this.gameFunctionsAll = response.data.gameFunctionsAll;
        this.playerGetTypeAll = response.data.playerGetTypeAll;
        // 如果当前正在编辑状态，刷新一下表单数据
        if (this.open && this.form.id) {
          console.log("字典加载完成，重新检查表单数据:", this.form);
        }
      }).catch(error => {
        console.error("获取字典数据失败:", error);
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        // projectDetail: "",
        // id: null,
        machineType: null,
        imgURL: null,
        // ParentId:null,
        isReserveASeat: null,
        isDeductCoin: null,
        isReCoin: null,
        isSettle: null,
        settleType: null,
        isScore: null,
        coinQuantity: [],
        gameFunctions: [],
        playerGetType: null,
      };
      this.resetForm("form");
    },
    // 点击某一行触发对应方法
    handleRowClick(row) {
      // //console.log(row.id)
      if (this.nameTypeID === 3 && row.id === 3) {
        this.nameTypeID = null;
      } else if (this.nameTypeID === 4 && row.id === 4) {
        this.nameTypeID = null;
      } else {
        this.nameTypeID = row.id;
      }
    },

    //图片上传前
    beforeUpload(file) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG/PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },

    //图片移除
    handleRemove(file) {
      //console.log(file);
    },
    //图片显示
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    //图片下载
    handleDownload(file) {
      //console.log(file);
    },
    //编辑修剪上传图片，选中文件触发的change事件
    handleAvatarChangeIcon(file, fileList) {
      const isJPG = file.raw.type === "image/jpeg";
      const isPNG = file.raw.type === "image/png";
      // const isLt2M = file.raw.size / 1024 / 1024 < 0.5  //限制上传文件的大小
      if (!isPNG && !isJPG) {
        this.$message.error("上传图片只能是 JPG/PNG 格式!");
        return false;
      } else {
        this.imgURL = URL.createObjectURL(file.raw); //赋值图片的url，用于图片回显功能
        this.uploadImg(file); //调用上传文件api接口
      }
    },
    uploadImg(file) {
      //文件上传操作
      let formData = new FormData();
      formData.append("file", file.raw);
      uploadImg(formData).then((res) => {
        this.form.imgURL = res.data.path;
      });
    },

    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.storeName = null;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加机台类型";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      
      getMachineType(id).then(response => {
        let data = response.data;
        // 处理JSON格式转为数组
        try {
          // 首先判断是否已经是数组
          if (Array.isArray(data.coinQuantity)) {
            // 确保数组元素是数字类型
            data.coinQuantity = data.coinQuantity.map(item => {
              return typeof item === 'string' ? Number(item) : item;
            });
          } 
          // 其次判断是否是字符串需要解析
          else if (typeof data.coinQuantity === 'string' && data.coinQuantity) {
            data.coinQuantity = JSON.parse(data.coinQuantity);            
            // 确保解析后的值与复选框期望的数据类型一致（转为数字类型）
            if (Array.isArray(data.coinQuantity)) {
              data.coinQuantity = data.coinQuantity.map(item => {
                // 如果item是字符串数字，转为数字
                return typeof item === 'string' ? Number(item) : item;
              });
            }
          } else {
            data.coinQuantity = [];
          }
          
          // 同样处理gameFunctions
          if (Array.isArray(data.gameFunctions)) {
            data.gameFunctions = data.gameFunctions.map(item => {
              return typeof item === 'string' ? Number(item) : item;
            });
          }
          else if (typeof data.gameFunctions === 'string' && data.gameFunctions) {
            data.gameFunctions = JSON.parse(data.gameFunctions);
            // 确保解析后的值与复选框期望的数据类型一致
            if (Array.isArray(data.gameFunctions)) {
              data.gameFunctions = data.gameFunctions.map(item => {
                return typeof item === 'string' ? Number(item) : item;
              });
            }
          } else {
            data.gameFunctions = [];
          }
        } catch (e) {
          // 解析失败时设置为空数组
          data.coinQuantity = [];
          data.gameFunctions = [];
        }
        // 确保所有字段都有效
        this.form = {
          ...this.form, // 保留默认值
          ...data, // 覆盖获取到的数据
        };
        this.open = true;
        this.title = "修改机台类型";
        
        // 强制更新视图
        this.$nextTick(() => {
          console.log("视图更新后的表单数据:", this.form);
        });
      }).catch(error => {
        console.error("获取数据出错:", error);
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          // 创建表单数据副本
          let formData = JSON.parse(JSON.stringify(this.form));
          // 根据错误信息调整，确保发送的是字符串格式的JSON
          // 错误信息表明后端需要String类型而不是数组
          if (Array.isArray(formData.coinQuantity)) {
            // 转换为JSON字符串
            formData.coinQuantity = JSON.stringify(formData.coinQuantity);
          } else if (!formData.coinQuantity) {
            formData.coinQuantity = '[]'; // 空数组的JSON字符串表示
          } else if (typeof formData.coinQuantity === 'object') {
            // 可能是响应式对象但不是数组
            formData.coinQuantity = JSON.stringify(Object.values(formData.coinQuantity));
          }
          
          if (Array.isArray(formData.gameFunctions)) {
            formData.gameFunctions = JSON.stringify(formData.gameFunctions);
          } else if (!formData.gameFunctions) {
            formData.gameFunctions = '[]';
          } else if (typeof formData.gameFunctions === 'object') {
            formData.gameFunctions = JSON.stringify(Object.values(formData.gameFunctions));
          }
          if (formData.id != null) {
            updateMachineType(formData).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            formData.userId = this.userId;
            formData.deptId = this.deptId;
            addMachineType(formData).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            }).catch(error => {
              this.$modal.msgError("新增失败"+error.response ? error.response.data : error);
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal
        .confirm('是否确认删除机台类型编号为"' + ids + '"的数据项？')
        .then(function () {
          return delMachineType(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        "machine/machineType/export",
        {
          ...this.queryParams,
        },
        `machineType_${new Date().getTime()}.xlsx`
      );
    },
    // 测试多个可能的WebSocket URL
    testWsUrls() {
      const possibleUrls = [
        'ws://localhost:8080/ws',
        'ws://localhost:8088/ws',
        'ws://localhost:8089/ws',
        'ws://localhost:9527/ws',
        'ws://localhost/ws',
        // 根据您的后端应用可能的端口添加更多
      ];
      
      this.testResults = [];
      
      possibleUrls.forEach(url => {
        try {
          console.log(`测试连接: ${url}`);
          const testWs = new WebSocket(url);
          
          testWs.onopen = () => {
            console.log(`${url} 连接成功!`);
            this.testResults.push({ url, status: '连接成功', success: true });
            // 发送一个简单的消息测试能否正常通信
            testWs.send(JSON.stringify({type: 'test'}));
            // 测试完关闭连接
            setTimeout(() => testWs.close(), 1000);
          };
          
          testWs.onerror = () => {
            console.log(`${url} 连接失败`);
            this.testResults.push({ url, status: '连接失败', success: false });
          };
        } catch (error) {
          console.error(`测试 ${url} 出错:`, error);
          this.testResults.push({ url, status: `测试出错: ${error.message}`, success: false });
        }
      });
    },
    
    // 切换WebSocket URL
    switchUrl(url) {
      this.closeWebSocket(); // 先关闭现有连接
      this.wsUrl = url;      // 更新URL
      this.connectWebSocket(); // 建立新连接
    },
  },
};
</script>

<style lang="scss" scoped>
.upload {
  font-size: 40px;
  margin-top: 20px;
  margin-left: 50px;
  border: 2px dashed #aaa;
  width: 150px;
  height: 150px;
  line-height: 130px;
}

/* 自定义输入框宽度 */
.custom-width-input {
  width: 280px !important;
}

/* 表单项标签靠左缩进 */
::v-deep .el-form-item__label {
  padding-left: 15px !important;
  text-align: left !important;
}

/* 玩家信息块 自定义样式 */
.block {
  display: flex;
  justify-content: space-evenly;
  align-items: center;

  .text {
    width: 200px;

    .text_top {
      margin-top: 4px;
    }

    .text_top,
    .text_bott {
      display: flex;
      align-items: center;
      border: 2px solid #ebeced;
      box-sizing: border-box;

      div {
        text-align: left;
      }

      .text_t_title,
      .text_b_title {
        background-color: #d3dce6;
        display: flex;
        align-items: center;
        justify-content: center;
        width: 80px;
      }

      .text_border {
        text-align: center;
        width: 120px;
      }
    }
  }
}
</style>
<style>
/* 图片去除背景色 */
.el-avatar {
  background-color: transparent;
}

/* 二级菜单添加背景颜色 */
.ali .el-table__row {
  background-color: #f5fbff !important;
}
/* 图片变形处理 */
.aliy .el-avatar > img {
  width: 100% !important;
}
</style>
